package org.lsy.controller;

import lombok.extern.slf4j.Slf4j;
import org.lsy.model.Order;
import org.lsy.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author SHIYUAN
 * @version 1.0
 */
@Controller
@Slf4j
@RequestMapping("order")
public class OrderController {

    private OrderService orderService;

    @Autowired
    OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @GetMapping({"","index"})
    public String index(){
        return "index";
    }

    @GetMapping("createOrder")
    public String createOrder(Model model) {
        try {
            String id = orderService.createOrder();
            model.addAttribute("id", id);
        }catch (Exception e) {
            log.error("创建订单失败，原因：{}", e.toString());
            return "/create/error";
        }
        return "/create/success";
    }

    @GetMapping ("payOrder/{id}")
    public String payOrder(@PathVariable String id, Model model) {
        try {
            boolean outdated = orderService.isOutdated(id);
            if (outdated) {
                List<Order> orderList = orderService.findOrderList();
                model.addAttribute("list", orderList);
                return "/pay/outdated";
            } else {
                orderService.payForOrder(id);
                return "/pay/success";
            }
        } catch (Exception e) {
            log.error("支付订单失败，原因：{}", e.toString());
            return "/pay/fails";
        }
    }
}
